using System;
using OccurrencesCore.Model;
using OccurrencesCore.Service;
using Telerik.Web.UI;
using OccurrencesWeb;
using System.Web.UI.WebControls;

namespace OccurrencesWeb.Page
{
    public partial class ApplicationConfigEdit : ExtendedPageBase
    {
        private const string LIST_PAGE_URL = "/Configuration";

        #region [ Properties ]

        public bool IsUpdate
        {
            get { return Convert.ToBoolean(ViewState[WebConstants.VS_IS_UPDATE]); }
            set { ViewState[WebConstants.VS_IS_UPDATE] = value; }
        }

        /// <summary>
        /// Application Config ID in case of Update action.
        /// </summary>
        public int ApplicationConfigID
        {
            get { return Convert.ToInt32(ViewState[WebConstants.KEY_APPLICATION_CONFIG_ID]); }
            set { ViewState[WebConstants.KEY_APPLICATION_CONFIG_ID] = value; }
        }

        #endregion

        #region [ Page Load ]

        protected void Page_Load(object sender, EventArgs e)
        {
            PopulateConfigType();
            if (!Page.IsPostBack)
            {
                string id = Page.RouteData.Values["id"] as string;
                if (!string.IsNullOrEmpty(id))
                {
                    try
                    {
                        ApplicationConfigID = Convert.ToInt32(id);
                    }
                    catch
                    {
                    }

                    IsUpdate = true;

                    PopulateWebForm(ApplicationConfigID);

                    //in case of update the system will disable some fields
                    txtApplicationConfigKey.Enabled = false;
                    txtApplicationConfigDescription.Enabled = false;
                    ddlConfigType.Enabled = false;
                }

                LoadValidators();
            }
        }

        #endregion

        #region [ Events ]

        protected void OnSaveClick(object sender, EventArgs e)
        {
            if (ValidateFields())
            {
                if (IsUpdate)
                    UpdateApplicationConfig();
                else
                    InsertApplicationConfig();
            }
        }

        protected void OnCancelClick(object sender, EventArgs e)
        {
            Context.Items.Add(WebConstants.KEY_GRID_PAGE_INDEX, PreviowsGridPageIndex);
            Response.Redirect(LIST_PAGE_URL);
        }

        #endregion

        #region [ Methods ]
        private void PopulateConfigType()
        {
            ddlConfigType.Items.Add(new ListItem(string.Empty, string.Empty));
            ddlConfigType.Items.Add(new ListItem("Boolean", "boolean"));
            ddlConfigType.Items.Add(new ListItem("Numeric", "numeric"));
            ddlConfigType.Items.Add(new ListItem("String", "string"));
        }

        /// <summary>
        /// Load all validator messages
        /// </summary>
        private void LoadValidators()
        {
            rfvApplicationConfigKey.ErrorMessage = string.Format(Resources.RequiredField, "Key");
            rfvApplicationConfigValue.ErrorMessage = string.Format(Resources.RequiredField, "Value");
            rfvApplicationConfigDescription.ErrorMessage = string.Format(Resources.RequiredField, "Description");
            rfvApplicationConfigType.ErrorMessage = string.Format(Resources.RequiredField, "Type");
        }

        /// <summary>
        /// Validade all input fields
        /// </summary>
        /// <returns></returns>
        private bool ValidateFields()
        {
            if (txtApplicationConfigDescription.Text.Length > 100)
            {
                ShowMessage(string.Format(Resources.MaximumCharactersExceeded, "Description", "100"), true);
            }

            return Page.IsValid;
        }

        /// <summary>
        /// Create and populate the ApplicationConfig object from the input fields
        /// </summary>
        private ApplicationConfiguration FillApplicationConfigObj()
        {
            ApplicationConfiguration applicationConfigObj = null;
            if (IsUpdate)
            {
                ApplicationConfigurationService configService = new ApplicationConfigurationService();
                applicationConfigObj = configService.FindByKey(ApplicationConfigID);
            }
            else
            {
                applicationConfigObj = new ApplicationConfiguration();
            }
            applicationConfigObj.Key = txtApplicationConfigKey.Text;
            applicationConfigObj.Value = txtApplicationConfigValue.Text;
            applicationConfigObj.Description = txtApplicationConfigDescription.Text;
            applicationConfigObj.Type = ddlConfigType.SelectedValue;

            return applicationConfigObj;
        }

        /// <summary>
        /// Clear all form fields 
        /// </summary>
        private void ClearFields()
        {
            txtApplicationConfigKey.Text = string.Empty;
            txtApplicationConfigValue.Text = string.Empty;
            txtApplicationConfigDescription.Text = string.Empty;
            ddlConfigType.ClearSelection();

        }

        /// <summary>
        /// Populate form with the received object
        /// </summary>
        private void PopulateWebForm(int applicationConfigID)
        {
            ApplicationConfiguration appConfig = new ApplicationConfigurationService().FindByKey(applicationConfigID);
            txtApplicationConfigKey.Text = appConfig.Key;
            txtApplicationConfigValue.Text = appConfig.Value;
            txtApplicationConfigDescription.Text = appConfig.Description;
            ddlConfigType.Items.FindByValue(appConfig.Type.ToString()).Selected = true;
        }

        /// <summary>
        /// Insert a new Application Config parameter
        /// </summary>
        private void InsertApplicationConfig()
        {
            try
            {
                ApplicationConfiguration applicationConfigObj = FillApplicationConfigObj();

                new ApplicationConfigurationService().Create(applicationConfigObj);

                ClearFields();

                Context.Items.Add(WebConstants.CTX_SHOW_MESSAGE_SUCCEEDED, true);
                Context.Items.Add(WebConstants.KEY_GRID_PAGE_INDEX, PreviowsGridPageIndex);
                Response.Redirect(LIST_PAGE_URL);
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message, true);
            }
        }

        /// <summary>
        /// Update a Application Config parameter
        /// </summary>
        private void UpdateApplicationConfig()
        {
            try
            {
                ApplicationConfiguration applicationConfigObj = FillApplicationConfigObj();

                new ApplicationConfigurationService().Update(applicationConfigObj);

                ShowMessage(Resources.OperationSucceeded, false);
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message, true);
            }
        }

        #endregion


    }
}
